package com.drm.netschool.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.drm.common.util.ConfigUtil;
import com.drm.common.util.CookieUtil;
import com.drm.common.util.DateUtil;
import com.drm.common.util.EncryptTool;
import com.drm.common.util.NumberUtil;
import com.drm.common.util.RegexUtil;
import com.drm.common.util.StringUtil;
import com.drm.common.util.constants.Constants;
import com.drm.netschool.entity.DrmArea;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.redis.RedisUtil;
import com.drm.netschool.service.DrmAreaService;
import com.drm.netschool.service.DrmSystemSettingService;
import com.drm.netschool.service.DrmUserService;
import com.drm.netschool.service.DrmUserSinfoService;
import com.drm.netschool.service.DrmUserUlogService;
import com.drm.netschool.service.mail.MailService;
import com.drm.netschool.web.form.RegisterForm;

/**
 * Created by CUIJB on 2015年7月25日
 */
@Controller
@RequestMapping("/member")
public class RegisterController {
	
	private Logger LOGGER = LoggerFactory.getLogger(RegisterController.class);
	
	@Autowired
	private DrmUserService userService;
	
	@Autowired
	private DrmUserSinfoService userInfoService;
	
	@Autowired
	private DrmUserUlogService userUlogService;
	
	@Autowired
	private DrmAreaService areaService;
	
	@Autowired
	private MailService mailService;
	
	@Autowired
	private DrmSystemSettingService systemSettingService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@RequestMapping(value = "/register")
    public String register(@ModelAttribute("form") RegisterForm form) {
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		try {
			//加载省信息
			List<DrmArea> areas = areaService.getProvinceList();
			form.setAreas(areas);
		} catch (Exception e) {
			LOGGER.error("查询省信息异常", e);
		}
        return "register/register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String doRegister(@ModelAttribute("form") RegisterForm form, HttpServletRequest request, HttpServletResponse response) {
    	form.setMetaInfo(systemSettingService.getDrmSystemSetting());
    	try {
    		//校验
    		Map<String, String> errors = check(form, request, response);
    		if(errors != null && errors.size() > 0){
    			form.setErrors(errors);
    			return "register/register";
    		}
    		
        	long userId = userService.addUser(form.getUser());
        	//添加DrmUserSinfo
        	userInfoService.add(userId);
        	//添加DrmUserUlog
        	userUlogService.add(userId);
        	
        	//发送激活邮件
        	String token = EncryptTool.md5Hex(EncryptTool.sha1HEX(DateUtil.dateToStr(DateUtil.current(), DateUtil.FORMAT_DEFAULT_MIN)));
   	     	String checkurl = Constants.DOMAIN + "/member/activate?token="+token+"&user.userId="+userId;
   	     	Map<String, Object> param = new HashMap<String, Object>();
   	     	param.put("url", checkurl);
   	     	param.put("userName", form.getUser().getUserLnm());
   	     	param.put("domain", Constants.DOMAIN);
   	     	mailService.sendMail("user-register-mail", param, form.getUser().getUserEmail(), true);
   	     	
   	     	//缓存激活链接的token & userId
   	     	redisUtil.setString(token, userId + "", 60*60*2);
		} catch (Exception e) {
			LOGGER.error(form.getUser().getUserLnm() + ",用户注册异常", e);
			form.putError("user_register", "系统异常!");
			return "register/register";
		}
        return "register/email-activate";
    }
    
    @RequestMapping(value = "/activate", method = RequestMethod.GET)
    public String activate(@ModelAttribute("form") RegisterForm form, HttpServletRequest request, HttpServletResponse response){
    	form.setMetaInfo(systemSettingService.getDrmSystemSetting());
    	if(form == null || form.getUser() == null || StringUtil.empty(form.getToken()) || NumberUtil.parseLong(form.getUser().getUserId()) == 0){
    		form.putError("email_activate", "链接参数有误,请重新发送激活邮件!");
    		return "";
    	}
    	try {
    		String userId = redisUtil.getString(form.getToken());
        	if(StringUtil.empty(userId)){
        		form.putError("email_activate", "链接已失效,请重新发送激活邮件!");
        		return "register/email-fail";
        	}
        	if(!userId.equals(form.getUser().getUserId()+"")){
        		form.putError("email_activate", "用户ID错误,请重新发送激活邮件!");
        		return "register/email-fail";
        	}
        	DrmUser user = userService.getById(form.getUser().getUserId());
        	if(user == null){
        		form.putError("email_activate", "用户数据错误,请重新发送激活邮件!");
        		return "register/email-fail";
        	}
        	user.setUserAvtive(1);
        	int result = userService.updateUser(user);
        	form.setUser(user);
        	if(result == 0){
        		form.putError("email_activate", "激活失败!");
        		return "register/email-fail";
        	}
		} catch (Exception e) {
			LOGGER.error(form.getUser().getUserId() + ",激活失败!", e);
			return "register/email-fail";
		}
    	return "register/email-suc";
    }
    
    @RequestMapping(value = "/send-activate-mail/{userId}", method = RequestMethod.GET)
    public String sendMail(@PathVariable Long userId, @ModelAttribute("form") RegisterForm form){
    	form.setMetaInfo(systemSettingService.getDrmSystemSetting());
    	try {
    		DrmUser user = userService.getById(userId);
        	if(user == null){
        		return "register/email-fail";
        	}
        	form.setUser(user);
        	
        	//发送激活邮件
        	String token = EncryptTool.md5Hex(EncryptTool.sha1HEX(DateUtil.dateToStr(DateUtil.current(), DateUtil.FORMAT_DEFAULT_MIN)));
         	String checkurl = Constants.DOMAIN + "/member/activate?token="+token+"&user.userId="+userId;
         	Map<String, Object> param = new HashMap<String, Object>();
         	param.put("url", checkurl);
         	param.put("userName", user.getUserLnm());
         	param.put("domain", Constants.DOMAIN);
         	mailService.sendMail("user-register-mail", param, user.getUserEmail(), true);
		} catch (Exception e) {
			LOGGER.error(userId + "邮件发送失败!", e);
		}
    	return "register/email-activate";
    }
    
    /*********************private**********************/
    
    private Map<String, String> check(RegisterForm form, HttpServletRequest request, HttpServletResponse response){
    	Map<String, String> result = new HashMap<String, String>();
    	if(form == null || form.getUser() == null){
    		result.put("userLnm", "参数错误");
    		return result ;
    	}
    	DrmUser user = form.getUser();
		if (StringUtil.empty(user.getUserLnm())) {
			result.put("userLnm", "用户名不能为空");
			return result ;
		} else if (StringUtil.empty(user.getUserMobile())) {
			result.put("userMobile", "手机号不能为空");
			return result ;
		}else if (!RegexUtil.isMobilePhone(user.getUserMobile())) {
			result.put("userMobile", "手机号格式有误");
			return result ;
		} else if (StringUtil.empty(user.getUserEmail())) {
			result.put("userEmail", "邮箱不能为空");
			return result ;
		} else if (!RegexUtil.isEmail(user.getUserEmail())) {
			result.put("userEmail", "邮箱格式有误");
			return result ;
		}else if (StringUtil.empty(user.getUserPass())) {
			result.put("userPass", "密码不能为空");
			return result ;
		} else if (StringUtil.empty(form.getConfirmPassword())) {
			result.put("confirmPassword", "确认密码不能为空");
			return result ;
		} else if (!user.getUserPass().equals(form.getConfirmPassword())) {
			result.put("confirmPassword", "密码和确认密码不一致");
			return result ;
		}
    	//校验用户名
    	CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_CHECKCODE);
    	String sRand = redisUtil.getString(key);
    	if(!sRand.equals(form.getCheckCode())){
    		result.put("userLnm", "校验码有误");
    		return result;
    	}
    	
    	DrmUser entity = userService.getByUserName(form.getUser().getUserLnm());
    	if(entity != null){
    		result.put("userLnm", "注册的用户名已经存在");
    		return result;
    	}
    	return null;
    }
}
